import 'dart:io';
import 'dart:ui';
import 'package:bruno/bruno.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:znmm/UI/A_Common/notFound_page.dart';
import 'package:znmm/UI/Other_APP/main2.dart';
import 'package:znmm/UI/utils/logger_service.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/UI/utils/sharedpre_utils.dart';
import 'package:znmm/config/app_init.dart';
import 'package:znmm/config/app_routes.dart';
import 'package:znmm/config/app_theme.dart';
import 'package:znmm/config/bloc/app_language_cubit.dart';
import 'package:znmm/config/bloc/app_mode_cubit.dart';
import 'package:znmm/config/bloc/app_theme_cubit.dart';
import 'package:znmm/config/strings.dart';
import 'package:znmm/generated/l10n.dart';

/*

这个代码定义了一个 IsarManager 类，
是一个单例模式（singleton）的工具类，用于管理 Isar 数据库。
Isar 是一个高性能的 Flutter 本地数据库，适合处理大量结构化数据。
本代码主要是对 Isar 数据库操作的封装，包括初始化、插入、查询、更新和删除等功能。

*/

Future<void> main() async {
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.presentError(details);
    throw details.exception; // 强制抛出异常
  };

  WidgetsFlutterBinding.ensureInitialized();

  //runApp(const MonekinAppEntryPoint());

  //这玩意是本地使用证书
  // ByteData data = await PlatformAssetBundle().load('assets/ca/fullchain.pem');
  // SecurityContext.defaultContext
  //     .setTrustedCertificatesBytes(data.buffer.asUint8List());

  await AppInit.init();

  if (!kIsWeb && Platform.isAndroid) {
    await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);

    var swAvailable = await AndroidWebViewFeature.isFeatureSupported(
        AndroidWebViewFeature.SERVICE_WORKER_BASIC_USAGE);
    var swInterceptAvailable = await AndroidWebViewFeature.isFeatureSupported(
        AndroidWebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);

    if (swAvailable && swInterceptAvailable) {
      AndroidServiceWorkerController serviceWorkerController =
          AndroidServiceWorkerController.instance();

      await serviceWorkerController
          .setServiceWorkerClient(AndroidServiceWorkerClient(
        shouldInterceptRequest: (request) async {
          return null;
        },
      ));
    }
  }

  //runApp(const MyApp());

  runApp(ScreenUtilInit(
    //designSize: const Size(414, 896),
    designSize: kIsWeb ? const Size(1440, 900) : const Size(414, 896),
    builder: (ctx, child) => const MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String? selectedMode = SharedPrefUtil().getData(SharedKey.strModeKey);
    //print("selectedMode0:$selectedMode");

    LoggerService.logInfo("------启动------");
    selectedMode = "dark";
    bool? bIsGuide = SharedPrefUtil().getData(SharedKey.strGuideKey);
    print("bIsGuide:$bIsGuide");

    // bool? bIsRemember = SharedPrefUtil().getData(SharedKey.strRemember);
    // print("bIsRemember:$bIsRemember");

    String strInitialRoute = RouteNames.loginRoute;
    // if (bIsGuide == null) {
    //   strInitialRoute = RouteNames.guideRoute;
    // }
    // else if (bIsRemember != null && bIsRemember) {
    //   UserInfoManage().localInInit();
    //   strInitialRoute = RouteNames.homeRoute;
    // }

    strInitialRoute = RouteNames.homeRoute;

    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (_) =>
              AppLanguageCubit(const Locale('en', 'US')), //..loadLanguage()
        ),
        BlocProvider(
          create: (_) => AppThemeCubit(material), //..loadTheme()
        ),
        BlocProvider(
          create: (_) =>
              AppModeCubit(selectedMode ?? c_systemStr), //..loadMode()
        ),
      ],
      child: BlocBuilder<AppThemeCubit, AppThemeState>(
        buildWhen: (previous, current) => previous != current,
        builder: (context, appTheme) {
          return BlocBuilder<AppModeCubit, AppModeState>(
            builder: (context, appMode) {
              return BlocBuilder<AppLanguageCubit, AppLanguageState>(
                builder: (context, language) {
                  print("------language:------${language.locale}");

                  return GestureDetector(
                      onTap: () {
                        //点击空白区域时隐藏键盘
                        final currentFocus = FocusScope.of(context);
                        if (!currentFocus.hasPrimaryFocus &&
                            currentFocus.hasFocus) {
                          FocusManager.instance.primaryFocus?.unfocus();
                        }
                      },
                      child: Shortcuts(
                        shortcuts: <LogicalKeySet, Intent>{
                          LogicalKeySet(LogicalKeyboardKey.select):
                              const ActivateIntent(),
                        },
                        child: GetMaterialApp(
                          title: "pintreel",
                          navigatorKey: gloNavigatorKey,
                          //.........多语言
                          //locale: const Locale('en', 'US'),
                          locale: language.locale,
                          supportedLocales: const [
                            Locale('zh', 'CN'),
                            Locale('en', 'US')
                          ],
                          localizationsDelegates: [
                            BrnLocalizationDelegate.delegate,
                            S.delegate,
                            GlobalMaterialLocalizations.delegate,
                            GlobalCupertinoLocalizations.delegate,
                            GlobalWidgetsLocalizations.delegate
                          ],
                          //.........end
                          scrollBehavior: CustomScroll(),
                          debugShowCheckedModeBanner: false,
                          themeMode: getMode(appMode.mode),
                          //theme: appTheme.theme.lightTheme,
                          theme: getThemeData(),
                          darkTheme: appTheme.theme.darkTheme,
                          builder: FlutterSmartDialog.init(
                              builder: EasyLoading.init()),
                          //home: const BottomNavigationDemo(),
                          initialRoute: strInitialRoute,
                          getPages: routePages,
                          unknownRoute: GetPage(
                              name: '/notfound',
                              page: () => const NotFoundPage()),
                        ),
                      ));
                },
              );
            },
          );
        },
      ),
    );
  }
}

class CustomScroll extends MaterialScrollBehavior {
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
        PointerDeviceKind.trackpad,
      };
}
